import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode cur = root;
        queue.offer(cur);
        while (!queue.isEmpty()) {
            int n = queue.size();
            int max = queue.peek().val;
            TreeNode t;
            for (int i = 0; i < n; i++) {
                t = queue.poll();
                if (t.left != null) queue.offer(t.left); 
                if (t.right != null) queue.offer(t.right);
                max = Math.max(max,t.val); 
            }
            list.add(max);
        }
        return list;
    }
}